package com.ruoyi.project.mobile.jiaqin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.R;
import com.ruoyi.project.jiaqin.area.domain.QuotationClassArea;
import com.ruoyi.project.jiaqin.area.service.IQuotationClassAreaService;
import com.ruoyi.project.jiaqin.company.domain.Company;
import com.ruoyi.project.jiaqin.company.service.ICompanyService;
import com.ruoyi.project.jiaqin.followmember.domain.JiaqinFollowMember;
import com.ruoyi.project.jiaqin.followmember.service.IJiaqinFollowMemberService;
import com.ruoyi.project.jiaqin.key.domain.ClassAttrKey;
import com.ruoyi.project.jiaqin.key.service.IClassAttrKeyService;
import com.ruoyi.project.jiaqin.numbertips.domain.NumberTips;
import com.ruoyi.project.jiaqin.numbertips.service.INumberTipsService;
import com.ruoyi.project.jiaqin.quotation.domain.Quotation;
import com.ruoyi.project.jiaqin.quotation.domain.QuotationSelectedBean;
import com.ruoyi.project.jiaqin.quotation.service.IQuotationService;
import com.ruoyi.project.jiaqin.quotationAvaPrice.domain.QuotationDayAvaBean;
import com.ruoyi.project.jiaqin.quotationAvaPrice.domain.QuotationDayAveragePrice;
import com.ruoyi.project.jiaqin.quotationAvaPrice.service.IQuotationDayAveragePriceService;
import com.ruoyi.project.jiaqin.quotationclass.domain.QuotationClass;
import com.ruoyi.project.jiaqin.quotationclass.service.IQuotationClassService;
import com.ruoyi.project.jiaqin.quotationlikes.domain.MemberQuotationLikes;
import com.ruoyi.project.jiaqin.quotationlikes.service.IMemberQuotationLikesService;
import com.ruoyi.project.jiaqin.thrclasstrend.domain.ThrClassTrend;
import com.ruoyi.project.jiaqin.thrclasstrend.service.IThrClassTrendService;
import com.ruoyi.project.jiaqin.twoclasstrend.domain.TwoClassTrend;
import com.ruoyi.project.jiaqin.twoclasstrend.service.ITwoClassTrendService;
import com.ruoyi.project.jiaqin.val.service.IClassAttrValService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/jq/quotation")
public class ApiQuotationController {

    public static final String countryId = "-100";

    @Autowired
    private IQuotationClassService iQuotationClassService;
    @Autowired
    private IClassAttrKeyService iClassAttrKeyService;
    @Autowired
    private IClassAttrValService iClassAttrValService;
    @Autowired
    private IQuotationService iQuotationService;
    @Autowired
    private ITwoClassTrendService iTwoClassTrendService;
    @Autowired
    private IThrClassTrendService iThrClassTrendService;
    @Autowired
    private IQuotationDayAveragePriceService iQuotationDayAveragePriceService;
    @Autowired
    private IQuotationClassAreaService iQuotationClassAreaService;
    @Autowired
    private ICompanyService companyService;

    /**
     * 行情: 获取一级分类列表
     * @return
     */
    @GetMapping("/getQuotationClassOne")
    public R getQuotationClassOne(){
        HashMap<String, Object> map = new HashMap<>();
        QuotationClass quotationClass = new QuotationClass();

        quotationClass.setLevel(0);
        List<QuotationClass> list = iQuotationClassService.selectQuotationClassList(quotationClass);
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * 行情: 获取二级或三级分类列表
     * @return
     */
    @GetMapping("/getQuotationClassByParentId")
    public R getQuotationClassByParentId(String parentId){
        HashMap<String, Object> map = new HashMap<>();
        QuotationClass quotationClass = new QuotationClass();
        quotationClass.setParentId(parentId);
        List<QuotationClass> list = iQuotationClassService.selectQuotationClassList(quotationClass);
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * 行情: 根据三级分类ID获取属性列表
     * @return
     */
    @GetMapping("/getClassAttrs")
    public R getClassAttrs(String quotationClassId){
        HashMap<String, Object> map = new HashMap<>();
        ClassAttrKey classAttrKey = new ClassAttrKey();
        classAttrKey.setQuotationClassId(quotationClassId);
        List<ClassAttrKey> list = iClassAttrKeyService.selectClassAttrKeyList(classAttrKey);
        map.put("data",list);
        return R.ok(map);
    }

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IJiaqinFollowMemberService jiaqinFollowMemberService;
    /**
     * 行情: 发布行情
     * @return
     *
     */
    @PostMapping("/releaseQuotation")
    public R releaseQuotation(@RequestBody Quotation quotation){
        // 不是会员，请先注册会员
        Member memberById = memberService.selectMemberById(quotation.getMemberId());
        if (memberById == null) {
            return R.error("请先注册");
        }
        if (memberById.getIsVip() == 0 && memberById.getIsJqVip() == 0) {
            return R.error("您不是会员，请先注册会员");
        }
        quotation.setReleaseDate(new Date());
        //根据用户ID和三级分类ID查询行情 用户是否发过
        Quotation lastQ = iQuotationService.selectQuotationByTwoId(quotation.getMemberId(),quotation.getClassIdThr());
        if(lastQ == null){
            //没有上一期直接发布
            return iQuotationService.insertQuotation(quotation)>0?R.ok():R.error("发布失败");
        }

        // 添加我的行情、关注行情数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(quotation.getMemberId());
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setQuotationNum(1);
            numberTipsService.updateNumberTips(tips);
        }
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setFollowMemberId(quotation.getMemberId());
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        if (followMemberList.size() > 0) {
            for (JiaqinFollowMember JFM : followMemberList) {
                JFM.setId(JFM.getId());
                JFM.setQuotationNum(1);
                jiaqinFollowMemberService.updateJiaqinFollowMember(JFM);
                NumberTips byMemberId = numberTipsService.selectNumberTipsByMemberId(JFM.getMemberId());
                if (byMemberId != null) {
                    NumberTips tips1 = new NumberTips();
                    tips1.setId(byMemberId.getId());
                    tips1.setFollowQuotationNum(1);
                    numberTipsService.updateNumberTips(tips1);
                }
            }
        }

        quotation.setLastPrice(lastQ.getPrice());
        BigDecimal cha = quotation.getPrice().subtract(lastQ.getPrice());
        quotation.setWavePrice(cha);
        //如果差值等于0
        if(cha.compareTo(new BigDecimal(0))==0){
            //昨天和今天价格相同
            quotation.setWavePerc(new BigDecimal(0.00));
            quotation.setStatus(0);
        }else if(cha.compareTo(new BigDecimal(0)) == 1){
            //昨天和今天价格不同 差大于零
            quotation.setWavePerc(quotation.getPrice()
                    .subtract(lastQ.getPrice())
                    .divide(lastQ.getPrice(),4,BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(100)));
            quotation.setStatus(1);
        }else{
            //差小于零
            quotation.setWavePerc(quotation.getPrice()
                    .subtract(lastQ.getPrice())
                    .divide(lastQ.getPrice(),4,BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(100)));
            quotation.setStatus(2);
        }
        return iQuotationService.insertQuotation(quotation)>0?R.ok():R.error("发布失败");
    }

    /**
     * 行情: 删除行情
     * @return
     *
     */
    @GetMapping("/deleteQuotation")
    public R deleteQuotation(String userId,String quotationId){
        return  iQuotationService.deleteQuotationById(quotationId)>0?R.ok("删除成功"):R.error("删除失败");
    }

    @Autowired
    private INumberTipsService numberTipsService;
    /**
     * 行情: 获取我的发布
     * @return
     */
    @GetMapping("/getMyQuotation")
    public R getMyQuotation(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String memberId,String myId){
        // 取消我的行情数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(memberId);
        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setQuotationNum(0);
            numberTipsService.updateNumberTips(tips);
        }
        // 取消关注行情数字提示
        if (myId != null && !myId.equals("")) {
            JiaqinFollowMember followMember = jiaqinFollowMemberService.selectJiaqinFollowMemberByMemberIdAndToMemberId(myId, memberId);
            if (followMember != null) {
                followMember.setQuotationNum(0);
                jiaqinFollowMemberService.updateJiaqinFollowMember(followMember);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        Quotation quotation = new Quotation();
        quotation.setMemberId(memberId);
        quotation.setDelFlag(0);
        PageHelper.startPage(pageNum,pageSize);
        List<Quotation> list = iQuotationService.selectQuotationList(quotation);
        PageInfo<Quotation> pageInfo = new PageInfo<>(list);
        map.put("data",pageInfo);
        return R.ok(map);
    }

    /**
     * 获取二级分类走势(七天/三十天/月度)
     * @param twoClassId
     * @return
     */
    @GetMapping("/getTwoClassTrendSevenDayByTwoClassId")
    public R getTwoClassTrendSevenDayByTwoClassId(String twoClassId,Integer type){
        HashMap<String, Object> map = new HashMap<>();
        if(type == 1) {
            //获取七天走势
            List<TwoClassTrend> list = iTwoClassTrendService.selectTwoClassTrendSevenDayByTwoClassId(twoClassId);
            map.put("data",list);
        }
        if (type == 2) {
            //获取三十天走势
            List<TwoClassTrend> list = iTwoClassTrendService.selectTwoClassTrendMonthDayByTwoClassId(twoClassId);
            map.put("data",list);
        }
        if(type == 3){
            //获取月度走势
//            List<>
            return R.error("暂无数据");
        }
        return R.ok(map);
    }

    /**
     * 根据二级分类ID获取所属三级分类走势
     * @param twoClassId
     * @return
     */
    @GetMapping("/getAllThrClassTrendByTwoClassId")
    public R getAllThrClassTrendByTwoClassId(String twoClassId){
        HashMap<String, Object> map = new HashMap<>();
        //查二级分类所属三级分类
        List<ThrClassTrend> list = iThrClassTrendService.selectThrClassTrendByTwoClassId(twoClassId);
        //查三级分类昨天的走势
        map.put("data",list);
        return R.ok(map);
    }

    /**
     * 获取三级分类走势(七天/三十天/月度)
     * @param twoClassId
     * @return
     */
    @GetMapping("/getThrClassTrendSevenDayByTwoClassId")
    public R getTrendForThrQClass(String thrClassId,Integer type){
        HashMap<String, Object> map = new HashMap<>();
        if(type == 1) {
//            //获取七天走势
            List<ThrClassTrend> list = iThrClassTrendService.selectThrClassTrendSevenDayByThrClassId(thrClassId);
            map.put("data",list);
        }
        if (type == 2) {
            //获取三十天走势
            List<ThrClassTrend> list = iThrClassTrendService.selectThrClassTrendMonthDayByThrClassId(thrClassId);
            map.put("data",list);
        }
        if(type == 3){
            //获取月度走势
//            List<>
            return R.error("暂无数据");
        }
        return R.ok(map);
    }


    /**
     * 根据三级分类获取行情列表
     */
    @GetMapping("/getQuotationByThrClassId")
    public R getQuotationByThrClassId(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String thrClassId,String memberId){
        HashMap<String, Object> map = new HashMap<>();
        Quotation quotation = new Quotation();
        quotation.setClassIdThr(thrClassId);
        PageInfo<Quotation> pageInfo = iQuotationService.selectQuotationListByThrClassId(pageNum,pageSize,thrClassId,memberId);
        map.put("data",pageInfo);
        return R.ok(map);
    }


    /**
     * 获取最新的六个价格指数
     */
    @GetMapping("/getQuotationRandomSix")
    public R getQuotatioRandomFive(){
        HashMap<String, Object> map = new HashMap<>();
        List<Quotation> list = iQuotationService.selectQuotationFive();
        map.put("data",list);
        return R.ok(map);
    }


    @Autowired
    private IMemberQuotationLikesService iMemberQuotationLikesService;
    /**
     * 用户点赞行情
     * @param userId
     * @param questionId
     * @return
     */
    @GetMapping("/likesQuotation")
    public R likesNews(String userId,String quotationId){
        MemberQuotationLikes memberQuotationLikes=  iMemberQuotationLikesService.selectMemberQuotationLikesById(userId,quotationId);
        if(memberQuotationLikes != null){
            return R.error("点赞失败:已经点过赞了");
        }
        MemberQuotationLikes memberQuotationLikes1= new MemberQuotationLikes();
        memberQuotationLikes1.setMemberId(userId);
        memberQuotationLikes1.setQuotationId(quotationId);
        iMemberQuotationLikesService.insertMemberQuotationLikes(memberQuotationLikes1);
//        return iQuotationService.likesQuotation(memberQuotationLikes)>0?R.ok("点赞成功"):R.error("点赞失败");
        return iQuotationService.likesQuotationLin(memberQuotationLikes1)>0?R.ok("点赞成功"):R.error("点赞失败");
    }

    /**
     * 用户取消点赞行情
     * @param userId
     * @param quotationId
     * @return
     */
    @GetMapping("/unlikesQuotation")
    public R unlikesNews(String userId,String quotationId){
        MemberQuotationLikes memberQuotationLikes=  iMemberQuotationLikesService.selectMemberQuotationLikesById(userId,quotationId);
        if(memberQuotationLikes == null){
            return R.error("取消失败:还未点赞");
        }

        iMemberQuotationLikesService.deleteMemberQuotationLikesById(memberQuotationLikes.getId());
//        return iQuotationService.unlikesQuotation(userId,quotationId)>0?R.ok("取消点赞成功"):R.error("取消点赞失败");
        Quotation quotation = iQuotationService.selectQuotationById(memberQuotationLikes.getQuotationId());
        if (quotation.getLikes() > 0){
            return iQuotationService.unlikesQuotationLin(memberQuotationLikes)>0?R.ok("取消点赞成功"):R.error("取消点赞失败");
        }else {
            return R.ok("取消点赞成功");
        }

    }

    /**
     * 查询行情分类-产地（批发市场等）列表
     */
    @GetMapping("/classArealist")
    public R list(QuotationClassArea quotationClassArea)
    {
        HashMap<String, Object> map = new HashMap<>();
        List<Object> resList = new ArrayList<>();
        List<QuotationClassArea> list = iQuotationClassAreaService.selectQuotationClassAreaList(quotationClassArea);
        for (QuotationClassArea QCA: list) {
            HashMap<String, Object> subMap = new HashMap<>();
            subMap.put("id",QCA.getId());
            subMap.put("name",QCA.getName());
            resList.add(subMap);
        }
        map.put("data",resList);
        return R.ok(map);
    }

    public QuotationDayAveragePrice getOneDayAveragePrice(String classAreaId, String classId, Date date, String cityId){
        QuotationDayAvaBean bean = new QuotationDayAvaBean();
        bean.setQuotationClassId(classId);
        bean.setQuotationClassAreaId(classAreaId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date currentDate = date;
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        int day1 = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day1 + 1);
        Date nextDate = c.getTime();

        bean.setStartStr(format.format(currentDate));
        bean.setEndStr(format.format(nextDate));
        bean.setStandardId("");
        bean.setQuotationCityId(cityId);
        List<QuotationDayAveragePrice> adps = iQuotationDayAveragePriceService.selectQuotationListByParams(bean);
        QuotationDayAveragePrice adp = null;
        if (adps.size() > 0){
            for (QuotationDayAveragePrice subAdp: adps) {
                adp = subAdp;
            }
        }
        return adp;
    }

    public void changeDayAcePriceDate(Quotation quotation){
        String classId = "";
        //除了绒，其他行情有1j和2j分类均价走势
        for (int i = 0; i <2 ; i++) {
            if (i == 0){
                classId = quotation.getClassIdOne();
            }
            if (i == 1){
                classId = quotation.getClassIdThr();
            }

            /*不再受用户之前是否发布限制、直接插入数据，一天只能插入一条，新的覆盖老得-----*/
            QuotationDayAveragePrice adp = this.getOneDayAveragePrice(Integer.toString(quotation.getClassAreaId()),classId,new Date(),quotation.getCityId());

            QuotationDayAveragePrice quotationDayAveragePrice = new QuotationDayAveragePrice();
            quotationDayAveragePrice.setDate(new Date());
            quotationDayAveragePrice.setQuotationClassAreaId((long) quotation.getClassAreaId());
            quotationDayAveragePrice.setQuotationClassId(classId);
            quotationDayAveragePrice.setQuotationStandardId("");
            if (adp != null) {
                BigDecimal insertPrice = quotation.getPrice();
                BigDecimal totlePrice = BigDecimal.valueOf(adp.getCount() * Double.parseDouble(adp.getDayAveragePrice()));
                BigDecimal count = BigDecimal.valueOf(adp.getCount() + 1);
                BigDecimal newAvaPrice = totlePrice.add(insertPrice).divide(count
                        , 2, BigDecimal.ROUND_HALF_UP);
                DecimalFormat df1 = new DecimalFormat("0.00");
                String newAvaPriceStr = df1.format(newAvaPrice);
                quotationDayAveragePrice.setDayAveragePrice(newAvaPriceStr);
                quotationDayAveragePrice.setCount(adp.getCount() + 1);
                quotationDayAveragePrice.setId(adp.getId());
                quotationDayAveragePrice.setQuotationCityId(adp.getQuotationCityId());
                iQuotationDayAveragePriceService.updateQuotationDayAveragePrice(quotationDayAveragePrice);
            } else {
                //今日首次插入数据加入lastDayPrice
                Date currentDate = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(currentDate);
                int day1 = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day1 - 1);
                Date lastDate = c.getTime();
                QuotationDayAveragePrice lastAdp = this.getOneDayAveragePrice(Integer.toString(quotation.getClassAreaId()), classId, lastDate,quotation.getCityId());
                if (lastAdp != null){
                    quotationDayAveragePrice.setLastDayAveragePice(lastAdp.getDayAveragePrice());
                }else {
                    quotationDayAveragePrice.setLastDayAveragePice("0");
                }

                quotationDayAveragePrice.setCount((long) 1);
                quotationDayAveragePrice.setDayAveragePrice(quotation.getPrice().toString());
                quotationDayAveragePrice.setQuotationCityId(quotation.getCityId());
                iQuotationDayAveragePriceService.insertQuotationDayAveragePrice(quotationDayAveragePrice);
            }
        }
    }

    public void changeCountryData(Quotation quotation){
        Quotation temp = new Quotation();
        BeanUtils.copyProperties(quotation, temp);
        temp.setCityId(countryId);
        this.changeDayAcePriceDate(temp);
    }

    /**
     * 行情: 发布行情
     *
     * @return
     */
    @PostMapping("/releaseQuotationLin")
    public R releaseQuotationLin(@RequestBody Quotation quotation) {
        Member memberById = memberService.selectMemberById(quotation.getMemberId());
        Company companyByMemberId = companyService.selectCompanyByMemberId(quotation.getMemberId());
        if (companyByMemberId != null) {
            if (companyByMemberId.getQuotation() == 1) {
                quotation.setReleaseDate(new Date());

                //改变cityId数据
                this.changeDayAcePriceDate(quotation);

                //改变全国数据
                this.changeCountryData(quotation);
            }
        } else if (memberById != null && memberById.getQuotation() ==1){
            quotation.setReleaseDate(new Date());

            //改变cityId数据
            this.changeDayAcePriceDate(quotation);

            //改变全国数据
            this.changeCountryData(quotation);
        }


        // 添加我的行情、关注行情数字提示
        NumberTips numberTips = numberTipsService.selectNumberTipsByMemberId(quotation.getMemberId());

        if (numberTips != null) {
            NumberTips tips = new NumberTips();
            tips.setId(numberTips.getId());
            tips.setQuotationNum(1);
            this.numberTipsService.updateNumberTips(tips);
        }
        JiaqinFollowMember followMember = new JiaqinFollowMember();
        followMember.setFollowMemberId(quotation.getMemberId());
        List<JiaqinFollowMember> followMemberList = jiaqinFollowMemberService.selectJiaqinFollowMemberList(followMember);
        if (followMemberList.size() > 0) {
            for (JiaqinFollowMember JFM : followMemberList) {
                JFM.setId(JFM.getId());
                JFM.setQuotationNum(1);
                jiaqinFollowMemberService.updateJiaqinFollowMember(JFM);
                NumberTips byMemberId = numberTipsService.selectNumberTipsByMemberId(JFM.getMemberId());
                if (byMemberId != null) {
                    NumberTips tips1 = new NumberTips();
                    tips1.setId(byMemberId.getId());
                    tips1.setFollowQuotationNum(1);
                    numberTipsService.updateNumberTips(tips1);
                }
            }
        }

        return iQuotationService.insertQuotation(quotation) > 0 ? R.ok() : R.error("发布失败");
    }

    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    public static int daysBetween(String smdate,String bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /*
     * 获取子分类下的信息
     * classId 父分类id
     * ClassAreaId 产地Id
     * city 所选城市
     * */
    @GetMapping("/getSubQuotationInfo")
    public R getSubQuotationInfo(String classId, String classAreaId, String cityId) throws ParseException{
        HashMap<String, Object> map = new HashMap<>();
        if (cityId.length() == 0){
            cityId = countryId;
        }
        List<Object> resList = new ArrayList<>();
        //获取子分类
        List<QuotationClass> subQuotationIds = iQuotationClassService.findSubQuotationIds(classId);
        for (QuotationClass QClass: subQuotationIds) {
            HashMap<String, Object> tempMap = new HashMap<>();
            QuotationDayAveragePrice adp = this.getOneDayAveragePrice(classAreaId,QClass.getId(),new Date(),cityId);
            if (adp != null){
                Double lastPrice = 0.00;
                Double dayPrice = 0.00;
                if (adp.getLastDayAveragePice().length() > 0){
                    lastPrice = Double.valueOf(adp.getLastDayAveragePice());
                }
                if (adp.getDayAveragePrice().length() > 0){
                    dayPrice = Double.valueOf(adp.getDayAveragePrice());
                }
                tempMap.put("lastPrice",lastPrice.toString());
                tempMap.put("nowPrice",dayPrice.toString());

                double upDownDouble = dayPrice-lastPrice;
                BigDecimal bg = new BigDecimal(upDownDouble);
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                String upDown = String.valueOf(f1);
                tempMap.put("upDown",upDown);
            }else {
                tempMap.put("lastPrice","0");
                tempMap.put("nowPrice","0");
                tempMap.put("upDown","0");

            }
            tempMap.put("classId",QClass.getId());
            tempMap.put("className",QClass.getName());
            resList.add(tempMap);
        }
        map.put("data",resList);
        return R.ok(map);
    }

    /*
     * 获取行情走势
     * classTypeId ：鸡鸭鹅..ID
     * classAreaId ： 产地ID
     * */
    @GetMapping("/getQuotationDaysByParamsLin")
    public R getQuotationDaysByParamsLin(Integer type, String classTypeId, String classAreaId, String startDay,String endDay, String cityId) throws ParseException {
        HashMap<String, Object> map = new HashMap<>();

        if (cityId.length() == 0){
            cityId = countryId;
        }

        if (type == 3) {
            //获取月度走势
//            List<>
            return R.error("暂无数据");
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

//        Calendar c2 = Calendar.getInstance();
//        c2.setTime(new Date());
//        int day2 = c2.get(Calendar.DATE);
//        c2.set(Calendar.DATE, day2 + 1);
//        String now= df.format(c2.getTime());
        String now = df.format(new Date());//现在

        String start = new String();//开始日

        int dayCount = 0;//相差天数

        if (type == 1){
            dayCount = 6;
        }
        if (type == 2) {
            dayCount = 29;
        }
        start = this.getPastDate(dayCount);

        if (type == 4){
            start = startDay;
            now = endDay;

            dayCount = daysBetween(start,now) + 1;
        }

        QuotationDayAvaBean bean = new QuotationDayAvaBean();
        bean.setStartStr(start);
        SimpleDateFormat sqlDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bean.setEndStr(sqlDf.format(new Date()));
        bean.setQuotationClassAreaId(classAreaId);
        bean.setQuotationClassId(classTypeId);
        bean.setQuotationCityId(cityId);
        bean.setStandardId("");
        //list sql结果集可能存在缺少日期的数据
        List<QuotationDayAveragePrice> list = iQuotationDayAveragePriceService.selectQuotationListByParams(bean);

        List<Object> resList = new ArrayList<>();

        Date nowDate = df.parse(now);//应该存在的结果日期-结束日期
        Date startDate = df.parse(start);//应该存在的结果日期-开始日期
        Date tempDate = startDate; //标记日期，用于对比
        if (list.size() > 0){
            //对比日期 查漏补缺
            for (int i = 0; i <list.size() ; i++) {
                QuotationDayAveragePrice pice = list.get(i);
                Date currentDate = df.parse(df.format(pice.getDate()));
                //比较当前日期和标记日期
                if (tempDate.before(currentDate)){
                    List<String> beforeList = getDays(df.format(tempDate),df.format(currentDate));
                    for (String beforeStr:beforeList) {
                        if (beforeStr.equals(df.format(pice.getDate()))){
                            HashMap<String, Object> resultMap = new HashMap<>();
                            resultMap.put("date",df.format(currentDate));
                            resultMap.put("avaPrice",pice.getDayAveragePrice());
                            resultMap.put("lastAvaPrice",pice.getLastDayAveragePice());
                            resList.add(resultMap);
                        }else{
                            HashMap<String, Object> resultMap1 = new HashMap<>();
                            resultMap1.put("date",beforeStr);
                            resultMap1.put("avaPrice","0");
                            resultMap1.put("lastAvaPrice","0");
                            resList.add(resultMap1);
                        }

                    }

                }else {
                    HashMap<String, Object> resultMap1 = new HashMap<>();
                    resultMap1.put("date",df.format(currentDate));
                    resultMap1.put("avaPrice",pice.getDayAveragePrice());
                    resultMap1.put("lastAvaPrice",pice.getLastDayAveragePice());
                    resList.add(resultMap1);
                }
                //比较完成，替换标记日期为 当前日期的后一天
                Date nextDay =  df.parse(df.format(currentDate));
                Calendar c = Calendar.getInstance();
                c.setTime(nextDay);
                int day1 = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day1 + 1);
                tempDate = c.getTime();
                //-------------

                //补最后一条sql数据后的空日期数据
                if ((list.size() - 1) == i){
                    if (currentDate.before(nowDate)){
                        List<String> beforeList = getDays(df.format(currentDate),df.format(nowDate));
                        for (String beforeStr:beforeList) {
                            if (!beforeStr.equals(df.format(currentDate))) {
                                HashMap<String, Object> resultMap1 = new HashMap<>();
                                resultMap1.put("date",beforeStr);
                                resultMap1.put("avaPrice","0");
                                resultMap1.put("lastAvaPrice","0");
                                resList.add(resultMap1);
                            }
                        }

                    }
                }
            }
        }else {
            tempDate = startDate;
            for (int i = 0; i <dayCount ; i++) {
                Date currentDate = tempDate;
                HashMap<String, Object> resultMap = new HashMap<>();
                resultMap.put("date",df.format(currentDate));
                resultMap.put("avaPrice","0");
                resultMap.put("lastAvaPrice","0");
                resList.add(resultMap);

                Date nextDay =  df.parse(df.format(currentDate));
                Calendar c = Calendar.getInstance();
                c.setTime(nextDay);
                int day1 = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day1 + 1);
                tempDate = c.getTime();
            }
        }


        double highestPrice = 0;
        double lowestPrice = 0;
        double avePrice = 0;
        double totlePrice = 0;
        for (Object subMap: resList) {
            HashMap<String, Object> temp = (HashMap<String, Object>) subMap;
            double tempPrice = Double.valueOf((String) temp.get("avaPrice"));
            if (tempPrice > highestPrice){
                highestPrice = tempPrice;
            }
            if (tempPrice < lowestPrice){
                lowestPrice = tempPrice;
            }

            totlePrice += tempPrice;
        }
        avePrice = totlePrice / resList.size();

//        HashMap<String, Object> quotationMap = new HashMap<>();
//        quotationMap.put("quotationList",resList);
//        quotationMap.put("avePrice", avePrice);
//        quotationMap.put("highestPrice", highestPrice);
//        quotationMap.put("lowestPrice", lowestPrice);
//        map.put("data", quotationMap);

        List<Object> reResultList = new ArrayList<>();


        for (Object subMap: resList) {
            HashMap<String, Object> temp = (HashMap<String, Object>) subMap;
            HashMap<String, Object> result = new HashMap<>();
            String lastAvaPrice = (String) temp.get("lastAvaPrice");
            String avaPrice = (String) temp.get("avaPrice");

            result.put("createBy","");
            result.put("createTime","");
            result.put("day",temp.get("date"));
            result.put("id","");
            result.put("lastdayAvgPrice",lastAvaPrice);
            result.put("params",new HashMap<>());
            result.put("searchValue","");
            result.put("status",type);
            result.put("todayAvgPrice",avaPrice);
            result.put("twoClassId","");
            result.put("updateBy","");
            result.put("updateTime","");
            Double wavePrice = Double.valueOf(avaPrice) -  Double.valueOf(lastAvaPrice);
            BigDecimal wavePerc = BigDecimal.valueOf(0.00);
            if (Double.valueOf(avaPrice) > 0){
                wavePerc = BigDecimal.valueOf(Double.valueOf(avaPrice)).subtract(BigDecimal.valueOf(Double.valueOf(lastAvaPrice)))
                        .divide(BigDecimal.valueOf(Double.valueOf(avaPrice)),4,BigDecimal.ROUND_UP)
                        .multiply(new BigDecimal(100));
            }

            result.put("wavePerc",String.valueOf(wavePerc));
            result.put("wavePrice",String.valueOf(wavePrice));
            reResultList.add(result);
        }
        map.put("data", reResultList);
        return R.ok(map);
    }

    //条件查询获取发布列表
    @GetMapping("/getQuotationReleaseByParams")
    public R getQuotationReleaseByParams(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            , @RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize, QuotationSelectedBean bean){

        HashMap<String, Object> map = new HashMap<>();
        PageInfo<Object> pageInfo = iQuotationService.getQuotationReleaseByParams(pageNum,pageSize,bean);
        map.put("data",pageInfo);
        return R.ok(map);
    }
}
